package tavernaPBS;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class TorqueConvert {
	
	// convert a PBS object into a String
	public static String fromPBS(TorquePBS thing) {
	
		// if no connection has been made, attempt one
		if (thing.getRemoteRootDirectory() == null) {
			try {
				thing.startLog();
			}
			catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		// save any updated config parameters
		if (thing.updatedConfig()) {
			try {
				thing.saveConfig();
			}
			catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		ByteArrayOutputStream byter = null;
		ObjectOutputStream out = null;
		
		try {
			byter = new ByteArrayOutputStream();
			out = new ObjectOutputStream(byter);
			out.writeObject(thing);
			out.close();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		
                BASE64Encoder encoder = new BASE64Encoder();
		return encoder.encode(byter.toByteArray());
	}
	
	// convert a String into a TorquePBS object
	public static TorquePBS toPBS(String pbsString) {
		
		TorquePBS thing = null;
		ByteArrayInputStream byter = null;
		ObjectInputStream in = null;
		
		try {
                    BASE64Decoder decoder = new BASE64Decoder();
			byter = new ByteArrayInputStream(decoder.decodeBuffer(pbsString));
			in = new ObjectInputStream(byter);
			thing = (TorquePBS)in.readObject();
			in.close();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		
		if (!Thread.currentThread().getName().equals("main")) {
		
			thing.setNodeName(nodeNameParser());
			thing.setNestedNode(nestNodeNameParser());
			
		}
		
		return thing;
	}
	
	// parse the threadname to extract the node name
	private static String nodeNameParser() {
		
		String reverse = new StringBuffer(Thread.currentThread().getName()).reverse().toString();
		
		String nodeName = new StringBuffer(reverse.substring(reverse.indexOf("[") + 1, reverse.indexOf(":"))).reverse().toString();
		
		return nodeName;
		
	}
	
	
	// this function will extract the name of the nest node
	// only detects one level of nesting
	private static String nestNodeNameParser() {
		
		String[] threadFields = Thread.currentThread().getName().split(":");
		
		if (threadFields.length > 3) {
			return threadFields[2];
		}
		else {
			return null;
		}
		
	}

}
